//
//  ZEmoticonBottoMView.swift
//  swift-weibo
//
//  Created by zero on 17/3/30.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

enum emoticonBottomTag:Int {
    
    case recent = 2000
    case normal = 2001
    case emoji = 2002
    case lxh = 2003
    
}

class ZEmoticonBottomView: UIStackView {


    //  默认选中的按钮
    var currentBtn:UIButton?
    
    //  联动滚动的闭包
    var scrolleTo:((Int)->())?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //  布局
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  设置button的tag
    func setButtonTag(buttonTag:Int) {
        
        // 通过tag 获取对应的按钮
        let button =  viewWithTag(buttonTag + 2000) as! UIButton

        
        if button != currentBtn {
            
            currentBtn?.isSelected = false
            button.isSelected = true
            currentBtn = button
        }
    }
    
    //  布局
    fileprivate func setupUI(){
     
        backgroundColor = UIColor.red
        
        // 设置布局的方式
        axis = .horizontal
        
        // 设置填充方式
        distribution = .fillEqually
        
        addSubview(getButton(title: "最近", imageName: "left", buttonTag: .recent))
        addSubview(getButton(title: "默认", imageName: "mid", buttonTag: .normal))
        addSubview(getButton(title: "emoji", imageName: "mid", buttonTag: .emoji))
        addSubview(getButton(title: "浪小花", imageName: "right", buttonTag: .lxh))
        
    }
    
}

extension ZEmoticonBottomView{
    
    fileprivate func getButton(title:String,imageName:String,buttonTag:emoticonBottomTag) -> UIButton{
        
        let btn = UIButton()
        
        btn.setTitle(title, for: .normal)
    
        btn.tag = buttonTag.rawValue
        
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.lightGray, for: .selected)
        btn.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imageName)_normal"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imageName)_selected"), for: .selected)
        
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        //  添加点击时间
        btn.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        //  默认选中
        if buttonTag == .normal {
            
            btn.isSelected = true
            
            currentBtn = btn
        }
        
        addArrangedSubview(btn)
        
        
        return btn
    }
    
    //  按钮点击事件
    @objc fileprivate func buttonClick(button:UIButton){
        
        if button != currentBtn {
            
            currentBtn?.isSelected = false
            button.isSelected = true
            currentBtn = button
        }
        
        
        scrolleTo?(button.tag)
    }
}
